#include "guacinput.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "SDL/SDL.h"

int input_update(lua_State *L)
{
    memset(keysDown, 0, sizeof(keysDown));
    memset(keysUp, 0, sizeof(keysUp));
    memset(mouseButtonsDown, 0, sizeof(mouseButtonsDown));
    memset(mouseButtonsUp, 0, sizeof(mouseButtonsUp));

    quitRequested = 0;

    SDL_Event ev;
    while (SDL_PollEvent(&ev))
    {
        switch(ev.type)
        {
            case SDL_KEYDOWN:
                keysDown[ev.key.keysym.sym]++;
                break;
            case SDL_KEYUP:
                keysUp[ev.key.keysym.sym]++;
                break;
            case SDL_MOUSEBUTTONDOWN:
                mouseButtonsDown[ev.button.button-1]++;
                break;
            case SDL_MOUSEBUTTONUP:
                mouseButtonsUp[ev.button.button-1]++;
                break;
            case SDL_QUIT:
                quitRequested = 1;
                break;
            case SDL_ACTIVEEVENT:
                switch(ev.active.state)
                {
                    case SDL_APPMOUSEFOCUS:
                        mouseOnScreen = ev.active.gain;
                        break;
                }
                break;
            case SDL_MOUSEMOTION:
                mouseOnScreen = 1;
                break;
        }
    }
    return 0;
}

static luaL_reg input_functions[] = {
    {"update", input_update},

    {NULL, NULL}
};

int luaopen_input(lua_State* L)
{
    luaL_register(L, "input", input_functions);

    return 1;
}
